<template>
  <div class="app-container">
    <!-- <aside>
      The guide page is useful for some people who entered the project for the first time. You can briefly introduce the
      features of the project. Demo is based on
      <a href="https://github.com/kamranahmedse/driver.js" target="_blank">driver.js.</a>
    </aside>
    <el-button icon="el-icon-question" type="primary" @click.prevent.stop="guide">
      Show Guide
    </el-button>-->
    <div class="head">
      <div class="head_left">
        <el-button @click="addStaffClick">新增员工</el-button>
        <el-dialog
          :title="titleType"
          :visible.sync="dialogVisible"
          class="dialogStyle"
        >
          <div class="box_input_one">
            <div>姓名:</div>
            <div class="divMargin">
              <el-input
                v-model="info.username"
                type="text"
                class="dialogInputClass"
              />
            </div>
            <div class="divMargin">性别:</div>
            <div class="divMargin styleMagin">
              <el-radio v-model="info.sex" label="男" border>男</el-radio>
              <el-radio v-model="info.sex" label="女" border>女</el-radio>
            </div>
            <div class="divMargin">年龄:</div>
            <div class="divMargin">
              <el-input
                v-model="info.age"
                type="text"
                class="dialogInputClass"
              />
            </div>
          </div>

          <div class="box_input_one">
            <div>所属部门:</div>
            <div class="divMargin styleMagin">
              <el-input
                v-model="info.department"
                type="text"
                class="dialogInputClass"
              />
            </div>
            <div class="divMargin">职位:</div>
            <div class="divMargin">
              <el-input
                v-model="info.position"
                type="text"
                class="dialogInputClass"
              />
            </div>
          </div>
          <div class="box_input_two">
            <div>手机号码:</div>
            <div class="divMargin">
              <el-input
                v-model="info.mobile"
                type="text"
                oninput="value=value.replace(/[^\d]/g,'')"
                maxlength="11"
                class="dialogInputClass"
              />
            </div>
            <div class="divMargin">入职日期:</div>
            <div class="divMargin">
              <el-date-picker
                v-model="info.entrydate"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
              />
            </div>
          </div>
          <div style="display: flex; flex-direction: row">
            <div class="box_input_two">
              <div>身份证号:</div>
              <div class="divMargin">
                <el-input
                  v-model="info.idcard"
                  type="text"
                  maxlength="18"
                  class="dialogInputClass"
                />
              </div>
            </div>
            <div class="box_input_two">
              <div style="margin-left: 10px">邮箱地址:</div>
              <div class="divMargin">
                <el-input
                  v-model="info.email"
                  type="text"
                  maxlength="18"
                  class="dialogInputClass"
                />
              </div>
            </div>
          </div>

          <div class="box_input_two">
            <div>家庭住址:</div>
            <div class="divMargin">
              <el-input
                v-model="info.address"
                type="text"
                class="dialogInputClass addressInput"
              />
            </div>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="addStaffCancel">取 消</el-button>
            <el-button type="primary" @click="addStaffConfrim">确 定</el-button>
          </div>
        </el-dialog>
      </div>
      <div class="head_right">
        <div class="box_search">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
          <div>
            <el-button @click="selectClick">查询</el-button>
          </div>
        </div>
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      :default-sort="{ prop: 'date', order: 'desce nding' }"
    >
      <el-table-column
        prop="username"
        label="姓名"
        width="70"
      />
      <el-table-column prop="sex" label="性别" width="50" />
      <!-- <el-table-column prop="age" label="年龄" width="50"></el-table-column> -->
      <el-table-column
        prop="mobile"
        label="手机"
        :show-overflow-tooltip="true"
        width="100"
      />
      <el-table-column
        prop="department"
        label="所属部门"
        width="80"
      />
      <el-table-column
        prop="position"
        label="职位"
        width="70"
      />
      <el-table-column
        prop="entrydate"
        label="入职日期"
        :formatter="formatDate"
        :filters="[
          { text: '本周', value: '本周' },
          { text: '本月', value: '本月' },
        ]"
      />
      <el-table-column
        prop="idcard"
        label="身份证"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="address"
        label="家庭住址"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="email"
        label="邮箱"
        width="50"
        :show-overflow-tooltip="true"
      />
      <el-table-column prop="integral" label="积分" sortable width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.integral < 0" style="color: red">{{
            scope.row.integral
          }}</span>
          <span v-else>{{ scope.row.integral }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="155">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleMark(scope.$index, scope.row)"
          >打分</el-button>
          <el-button
            type="text"
            size="small"
            @click="handleGroup(scope.$index, scope.row)"
          >分组</el-button>
          <el-button
            type="text"
            size="small"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>

      <el-dialog
        title="分组"
        :visible.sync="dialogTableVisibleGroup"
        :append-to-body="true"
      >
        <span style="font-size: 16px">姓名:</span><br>
        <el-input
          v-model="info.rolesName"
          class="inputValue"
          :disabled="true"
        />
        <!-- :row-class-name="tableRowClassName" -->
        <el-table :data="tableDataGroup">
          <el-table-column
            prop="id"
            label="ID"
            align="center"
            width="150"
          />
          <el-table-column
            prop="username"
            label="姓名"
            width="200"
            align="center"
          />
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="155"
          >
            <template slot-scope="scope">
              <el-button
                v-show="scope.row.flag_select"
                type="primary"
                size="small"
                @click="handleSelectGroup(scope.$index, scope.row)"
              >
                <!-- v-if="checkId(scope.$index, scope.row)" -->
                选择
              </el-button>
              <el-button
                v-show="scope.row.flag_delete"
                type="danger"
                size="small"
                @click="handleDeleteGroup(scope.$index, scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="display: flex; flex-direction: row">
          <div class="pagination">
            <el-pagination
              ref="pagerGroup"
              background
              :current-page="pageIndexGroup"
              :page-size="pageSizeGroup"
              :total="totalGroup"
              layout="prev, pager, next"
              @size-change="sizeChangeHandleGroup"
              @current-change="currentChangeHandleGroup"
            />
          </div>
          <span
            slot="footer"
            style="width: 600px; margin-left: 290px; margin-top: 10px"
            class="dialog-footer"
          >
            <el-button @click="cancelRoles">取 消</el-button>
            <el-button type="primary" @click="confirmRoles">确 定</el-button>
          </span>
        </div>
      </el-dialog>

      <el-dialog
        class="dialogIntegral"
        title="打分"
        :visible.sync="dialogVisibleIntegral"
        :append-to-body="true"
      >
        <el-radio-group v-model="info.arithmetic">
          <el-radio-button label="加分" />
          <el-radio-button label="减分" />
        </el-radio-group>
        <div style="margin: 20px 20px 20px 0px" />
        <el-input
          v-model="info.integrals"
          type="text"
          class="dialogInputClass addressInput"
          placeholder="请输入分数"
        />

        <div style="font-size: 16px">
          <div style="margin: 20px 20px 20px 0px">原因:</div>
          <div class="divMargin">
            <el-input
              v-model="info.reason"
              type="text"
              class="dialogInputClass addressInput"
            />
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addStaffCancelIntegral">取 消</el-button>
          <el-button
            type="primary"
            @click="addStaffConfrimIntegral"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-table>
    <div class="pagination">
      <el-pagination
        ref="pager1"
        background
        :current-page="pageIndex"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>
  </div>
</template>

<script>
import Driver from 'driver.js' // import driver.js
import 'driver.js/dist/driver.min.css' // import driver.js css
import steps from './steps'
import {
  getUserInfo,
  addUserInfo,
  deleteUserInfo,
  updateUserInfo,
  searchInfo,
  getUserPage,
  updateIntegral,
  getUserGroupPage,
  selectRoles,
  insertRoles,
  getUserInfoGroup
} from '@/api/info'

export default {
  name: 'Guide',
  data() {
    return {
      titleType: '新增员工', // 动态修改dialog框的标题
      driver: null,
      search: '',
      pageIndex: 1,
      pageSize: 2,
      total: 0,
      pageIndexGroup: 1,
      pageSizeGroup: 2,
      totalGroup: 0,
      rolesName: {},
      inputValue: '',
      rolesId: [], // 选中组员的id
      rolesArr: [], // 选中组员的姓名
      // 人员信息
      info: {
        id: '',
        username: '',
        age: '',
        sex: '',
        idcard: '',
        address: '',
        position: '', // 职位
        mobile: '',
        entrydate: '', // 入职日期
        department: '', // 部门
        email: '',
        arithmetic: '', // 算法
        reason: '',
        integrals: '' // 打分
      },
      dialogVisible: false,
      dialogVisibleIntegral: false,
      dialogTableVisibleGroup: false,
      tableData: [],
      tableDataGroup: [],
      roles: [],
      indexArr: []
    }
  },

  watch: {
    scope() {}
  },
  mounted() {
    this.driver = new Driver()
  },
  // 创建页面时，查询数据 渲染到组件
  created() {
    this.selectUserInfo()
  },

  methods: {
    // 取消dialog弹框
    cancelRoles() {
      this.dialogTableVisibleGroup = false
    },
    // 提交分组信息
    confirmRoles() {
      new Promise((resolve, reject) => {
        insertRoles({
          id: this.info.id,
          rolesId: this.rolesId,
          rolesName: this.info.rolesName
        }).then((response) => {
          location.reload()
          //  this.handleGroup();
        })
      })
    },
    // 选择组员
    handleSelectGroup($index, row) {
      // console.log($index);
      row.flag_select = false
      row.flag_delete = true
      this.rolesArr.push(row.username) // 当前选中用户姓名放进数组
      // console.log(this.rolesId);
      this.rolesId.push(row.id) // 当前选中的用户id放进数组
      this.info.rolesName = this.rolesArr.join(',') // 将姓名数组转换成字符串 v-model双向绑定inpit框
      // console.log("2112132131");
      // console.log(this.rolesId);
      // console.log(row.flag_delete);
      // console.log(row.flag_select);
    },

    // 删除组员
    handleDeleteGroup($index, row) {
      row.flag_select = true
      row.flag_delete = false
      // console.log(row.flag_delete);
      // console.log(row.flag_select);
      // console.log(this.rolesArr);
      // 点击删除先删除用户组的用户id
      for (let i = 0; i < this.rolesId.length; i++) {
        if ((this.rolesId[i] = row.id)) {
          this.rolesId.splice(i, 1)
        }
      }
      // 删除用户组的用户姓名
      for (let i = 0; i < this.rolesArr.length; i++) {
        // console.log("第一次");
        // console.log(this.rolesArr[i]);
        // console.log(row.username);
        // 当用户数组中存在和当前行的用户姓名相同时删除
        if (this.rolesArr[i] == row.username) {
          // console.log(this.rolesArr);
          this.rolesArr.splice(i, 1)
          // console.log("12132131313213");
          // console.log(this.rolesArr);
          // console.log(this.rolesId);
          // 将数组转换成字符串 使用 join
          const str = this.rolesArr.join(',')
          // console.log(str);
          this.info.rolesName = str
        }
      }
    },
    // 分组
    handleGroup($index, row) {
      this.dialogTableVisibleGroup = true
      // 获取当前要分组的用户的信息
      this.info = Object.assign({}, row)
      // 获取全部人员信息
      new Promise((resolve, reject) => {
        getUserInfoGroup({ id: this.info.id })
          .then((response) => {
            // console.log("13213131313131313");
            this.tableDataGroup = response.data.data
            // console.log(this.tableDataGroup[0].id);
            // console.log(this.info.roles);

            if (this.info.roles == null || this.info.roles == '') {
            }
            // console.log(1231131321);
            // console.log(this.info.roles);
            // 当该用户没有组员时 将按钮全部变为可以选择组员
            if (this.info.roles == null || this.info.roles == '') {
              this.info.roles = null
              for (let i = 0; i < this.tableDataGroup.length; i++) {
                this.tableDataGroup[i].flag_delete = false
                this.tableDataGroup[i].flag_select = true
              }
            }
            // 当有组员时 将该用户的组员id 放进数组中进行操作 使用split
            this.rolesId = this.info.roles.split(',')

            // 当有组员时需要改变当前行按钮的状态 使用循环来判断 如果存放组员的id的数组和当前行的用户的id相同时
            // 代表该成员属于当前用户 将按钮变为删除状态 反之则变为选择
            for (let j = 0; j < this.rolesId.length; j++) {
              // console.log(888888888);
              for (let i = 0; i < this.tableDataGroup.length; i++) {
                // console.log(this.tableDataGroup[i]);
                // console.log(this.rolesId[j]);
                // console.log("");
                if (this.rolesId[j] == this.tableDataGroup[i].id) {
                  // 改变按钮状态
                  this.tableDataGroup[i].flag_delete = true
                  this.tableDataGroup[i].flag_select = false
                }
              }
            }
            // 分页和总数
            this.totalGroup = response.data.total
            this.pageSizeGroup = response.data.to
            // console.log("xhaskdhkskj");
            // console.log(this.rolesId);
            // 字符串转为数组
            this.rolesArr = this.info.rolesName.split(',')
            // console.log(this.rolesArr);
          })
          .then((response) => {
            // 查询完所有用户信息后 查询当前要分组的人的分组信息
            // this.selectUserRoles();
            // this.checkId()
          })
      })
    },
    selectUserRoles() {
      new Promise((resolve, reject) => {
        selectRoles({ id: this.info.id }).then((response) => {})
      })
    },
    // 打分
    handleMark($index, row) {
      this.dialogVisibleIntegral = true
      this.info = Object.assign({}, row)
    },

    addStaffCancelIntegral() {
      this.dialogVisibleIntegral = false
      this.info = ''
    },
    addStaffConfrimIntegral($index, row) {
      new Promise((resolve, reject) => {
        updateIntegral(this.info).then((response) => {
          this.selectUserInfo()
        })
      }).catch(() => {
        console.log('CodeMirror-overlayscroll-horizontal')
      })
      this.dialogVisibleIntegral = false
      this.info = ''
    },

    // 查询信息
    selectUserInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo().then((response) => {
          this.tableData = response.data.data
          this.total = response.data.total
          this.pageSize = response.data.to
          this.totalGroup = response.data.total
          this.pageSizeGroup = response.data.to
        })
      })
    },
    // 下一页
    sizeChangeHandle: function(size) {
      this.pagesize = size
    },
    sizeChangeHandleGroup(size) {
      this.pageSizeGroup = size
    },
    currentChangeHandleGroup: function(val) {
      return new Promise((resolve, reject) => {
        getUserGroupPage(val, { id: this.info.id }).then((response) => {
          this.tableDataGroup = response.data.data
          // this.inputValue = this.info.rolesName;
          // this.rolesArr = this.inputValue.split(",");
          // let infoArr = this.info.roles.split(",");
          // console.log(infoArr);
          for (let i = 0; i < this.tableDataGroup.length; i++) {
            for (let j = 0; j < this.rolesId.length; j++) {
              if (this.rolesId[j] == this.tableDataGroup[i].id) {
                this.tableDataGroup[i].flag_delete = true
                this.tableDataGroup[i].flag_select = false
              }
              // else {
              //   this.tableDataGroup[i].flag_delete = false;
              //   this.tableDataGroup[i].flag_select = true;
              // }
            }
          }
        })
      })
    },
    currentChangeHandle: function(val) {
      // this.pageIndex = val;
      // // this.selectUserInfo();
      // console.log("index" + this.pageIndex);
      return new Promise((resolve, reject) => {
        getUserPage(val).then((response) => {
          this.tableData = response.data.data
        })
      })
    },
    // 编辑信息
    handleEdit($index, row) {
      this.titleType = '编辑信息'
      this.dialogVisible = true
      if (this.titleType == '编辑信息') {
        this.info = Object.assign({}, row)
        // console.log(this.info);
      }
    },
    // 删除信息
    handleDelete($index, row) {
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          new Promise((resolve, reject) => {
            deleteUserInfo(row).then((response) => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.selectUserInfo()
            })
          })
        })
        .catch((err) => {
          console.error(err)
        })
    },

    guide() {
      this.driver.defineSteps(steps)
      this.driver.start()
    },
    addStaffClick() {
      this.titleType = '新增员工'
      this.dialogVisible = true
      this.info = {
        id: '',
        username: '',
        age: '',
        sex: '',
        idcard: '',
        address: '',
        position: '', // 职位
        mobile: '',
        entrydate: '', // 入职日期
        department: '', // 部门
        email: '',
        arithmetic: '', // 算法
        reason: '',
        integrals: '' // 打分
      }
    },
    // dialog的确认事件
    addStaffConfrim() {
      // console.log(this.titleType);
      if (this.titleType == '新增员工') {
        // console.log("新增");
        this.dialogVisible = false
        return new Promise((resolve, reject) => {
          addUserInfo(this.info).then((response) => {
            this.dialogVisible = false
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            // location.reload();
            this.selectUserInfo()
          })
        })
      } else {
        new Promise((resolve, reject) => {
          updateUserInfo(this.info).then((response) => {
            this.dialogVisible = false
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            // location.reload()
            this.selectUserInfo()
          })
        })
      }
    },
    // dialog的取消事件
    addStaffCancel() {
      this.dialogVisible = false
      this.info = ''
    },

    filterHandler() {},
    // 条件查询信息
    selectClick() {
      // console.log("查询的条件");
      // console.log(this.search);
      var arr = this
      return new Promise((resolve, reject) => {
        searchInfo({ search: this.search }).then((response) => {
          // console.log("查询成功");
          // console.log({ search: this.search });
          arr.tableData = response.data.data
          arr.total = response.data.total
          arr.pageSize = response.data.to
          arr.search = ''
          // console.log(arr.tableData);
          // console.log(this.tableData);
        })
      })
    },
    formatDate(row, column) {
      // 获取单元格数据
      const data = row[column.property]
      if (data == null) {
        return null
      }
      // 对日期单元格进行简单的处理
      const dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    }
  }
}
</script>

<style >
.el-table .success-row {
  background: #f0f9eb;
}
.el-table .success-row:hover {
  background: none;
}
.app-container th {
  text-align: center !important;
}
.app-container td {
  text-align: center !important;
}
.app-container .btn .btnFooter {
  /* border: 1px solid red; */
  margin-top: 5px;
}
.app-container .el-input__inner {
  width: 250px;
  height: 30px;
  margin-right: 10px;
}
.app-container .head {
  display: flex;
  flex-direction: row;
  width: 100%;
  line-height: 40px;
  height: 40px;
  align-items: center;
}
.app-container .head .head_left {
  width: 40%;
}
.app-container .head .head_right {
  width: 60%;
  display: flex;
  flex-direction: row;
}
.app-container .head .title {
  width: 55px;
  color: #5f5d5d;
}
.app-container .head .box_search {
  display: flex;
  flex-direction: row;
}
.app-container .head .head_left .el-button {
  width: 100px;
  height: 30px;
  text-align: center;
  line-height: 8px;
}
.app-container .head .head_right .el-button {
  width: 80px;
  height: 30px;
  text-align: center;
  line-height: 8px;
}
.app-container .head .box_input_one {
  display: flex;
  flex-direction: row;
}
.app-container .head .box_input_one .el-input__inner {
  width: 129px;
}
.app-container .head .box_input_one .divMargin {
  margin-left: 10px;
}
.app-container .head .box_input_two {
  display: flex;
  flex-direction: row;
}
.app-container .head .box_input_two .el-input__inner {
  width: 180px;
}
.app-container .head .box_input_two .divMargin {
  margin-left: 10px;
}
.el-radio--medium.is-bordered {
  height: 30px;
  padding: 8px 10px 0px 5px;
  margin: 0;
}
.addressInput .inputValue .el-input__inner {
  width: 300px;
}
.inputValue {
  width: 550px;
  opacity: 1;
  margin-top: 10px;
  background: white;
  -webkit-text-fill-color: #333333;
}
</style>
